package com.phpxiu.app.view;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Toast;

import com.phpxiu.app.api.OnDialogClickListener;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.Net;
import com.phpxiu.app.model.Permission;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.dialog.Alert;
import com.phpxiu.app.view.dialog.InteractiveDialog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @file
 * @brief Activity的基本功能封装
 * @author 吴金洲
 * @note Activity的基本功能封装
 *
 */
public class UIBase extends FragmentActivity {
    protected Handler handler;
    protected BroadcastReceiver mReceiver;
    protected Alert mAlert;
    protected InteractiveDialog mInteractiveDlg;
    private int net;//网络类型
    protected long start=0L;
    private List<String> deniedPermissions=new ArrayList<String>();//被拒绝的权限
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        start=System.currentTimeMillis();
        handler=new IHandler(this);
        configLanguage();
        initReceiver();
    }

    /**
     * 匹配语言
     */
    protected void configLanguage(){
        SharedPreferences sp=getSharedPreferences(UserSetting.KKY_USER_LANGUAGE_CONFIG,MODE_PRIVATE);
        int code=sp.getInt(UserSetting.KKY_CURRENT_LANGUAGE_CODE,0);
        Resources resources =getResources();//获得res资源对象
        Configuration config = resources.getConfiguration();//获得设置对象
        DisplayMetrics dm = resources.getDisplayMetrics();//获得屏幕参数：主要是分辨率，像素等。
        switch (code){
            case 1:
                config.locale = Locale.SIMPLIFIED_CHINESE; //简体中文
                break;
            case 2:
                config.locale = Locale.ENGLISH;
                break;
            default:
                config.locale= Locale.getDefault();
                break;
        }
        resources.updateConfiguration(config, dm);
    }

    /**
     * 初始化广播监听，如果需要监听，在子界面onCreate(Bundle savedInstanceState){}调用此方法
     */
    protected void initReceiver() {
        mReceiver = new UIBroadcastReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);//默认只监听网络状态
        filter.addAction(Constants.BD_EXIT_APP);//广播退出应用程序
        filter.addAction(Constants.BD_LOG_OUT);//广播退出登录
        filter.addAction(Constants.BD_FORCE_LOG_OUT);//广播强制被登录出
        registerReceiver(mReceiver, filter);
    }

    /**
     * 警告提示
     */
    public void alert(String msg,View.OnClickListener clickListener){
        if(isFinishing()){
            return;
        }
        if(mAlert==null){
            mAlert=new Alert(this);
            mAlert.getWindow().getAttributes().width=(int) KKYApp.getInstance().screenWidth;
        }else {
            if(mAlert.isShowing()){
                mAlert.dismiss();
            }
        }
        mAlert.setMsg(msg);
        mAlert.setOnClickListener(clickListener);
        mAlert.show();
    }

    /**
     * 显示交互对话框
     * @param title 对话信息标题
     * @param desc 对话信息
     * @param callBack 确定、取消事件按钮回调
     */
    protected void interactiveDialog(String title,String desc,OnDialogClickListener callBack){
        if(isFinishing()){
            return;
        }
        if(mInteractiveDlg==null){
            mInteractiveDlg=new InteractiveDialog(this);
            mInteractiveDlg.getWindow().getAttributes().width=(int) KKYApp.getInstance().screenWidth;
        }else {
            if(mInteractiveDlg.isShowing()){
                mInteractiveDlg.dismiss();
            }
        }
        mInteractiveDlg.setTitle(title);
        mInteractiveDlg.setSummary(desc);
        mInteractiveDlg.setOnDialogClickListener(callBack);
        mInteractiveDlg.show();
    }

    /**
     * 显示交互对话框
     *
     * @param title 对话信息标题
     * @param desc 对话信息
     * @param ok 确定按钮标题
     * @param cancel 取消按钮标题
     * @param callBack 确定、取消事件按钮回调
     */
    protected void interactiveDialog(String title,String desc,String ok,String cancel,OnDialogClickListener callBack){
        if(isFinishing()){
            return;
        }
        if(mInteractiveDlg==null){
            mInteractiveDlg=new InteractiveDialog(this);
        }else {
            if(mInteractiveDlg.isShowing()){
                mInteractiveDlg.dismiss();
            }
        }
        mInteractiveDlg.setTitle(title);
        mInteractiveDlg.setSummary(desc);
        mInteractiveDlg.setOkTitle(ok);
        mInteractiveDlg.setCancelTitle(cancel);
        mInteractiveDlg.setOnDialogClickListener(callBack);
        mInteractiveDlg.show();
    }

    /**
     * 检测危险权限
     * @param code 请求代码
     */
    protected void requestMyPermissions(int code){
        switch (code){
            case Permission.REQUEST_COMMON:
                checkMyPermission(code,Permission.COMMON);
                break;
            case Permission.REQUEST_LOCATION:
                checkMyPermission(code,Permission.LOCATION);
                break;
            case Permission.REQUEST_PHOTO:
                checkMyPermission(code,Permission.PHOTO);
                break;
            case Permission.REQUEST_STORE:
                checkMyPermission(code,Permission.STORE);
                break;
        }
    }

    /**
     * 取到未授权的项
     * @param permissions
     */
    final private void checkMyPermission(int code,String[] permissions){
        deniedPermissions.clear();
        for (String p:permissions){
            int state= ActivityCompat.checkSelfPermission(this,p);
            if(state!=PackageManager.PERMISSION_GRANTED){
                deniedPermissions.add(p);
            }
        }
        if(deniedPermissions.size()!=0){
            try {
                requestPermissions(deniedPermissions.toArray(new String[1]),code);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            onPermission(code);
        }
    }


    /**
     * 显示通知
     * @param title
     * @param msg
     */
    private void notification(int id,String title,String msg){
        NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(KKYApp.getInstance());
        mBuilder.setContentTitle(title)//设置通知栏标题
                .setContentText(msg)
                .setTicker(msg) //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSmallIcon(R.mipmap.ic_launcher);//设置通知小ICON
        Notification notify = mBuilder.build();
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(id,notify);
    }

    /**
     *权限申请通过
     */
    protected void onPermission(int requestCode){}

    /**
     * 切换为没有网络状态
     */
    protected void onChangeToNone() {
        KKYUtil.log("切换为断开网络状态");
        Toast.makeText(this,getString(R.string.internet_disconnected),Toast.LENGTH_LONG).show();
    }

    /**
     * 切换为无线网络状态
     */
    protected void onChangeToWifi() {
        KKYUtil.log("切换为无线网络状态");
    }

    /**
     * 切换为流量计费网络状态(手机移动网络：2G、3G、4G及其它)
     */
    protected void onChangeToMobile() {
        KKYUtil.log("切换为流量计费网络状态");
    }

    /**
     * 退出应用程序
     */
    public void onExitApp(){
        finish();
    }

    /**
     * 主动退出登录
     */
    public void onLogOut(){
        finish();
    }

    /**
     * 强制被动退出登录
     */
    public void onForceLogOut(){
        finish();
    }


    /**
     * 线程消息处理
     * @param msg
     */
    public void handleMsg(Message msg){}

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isPermission=true;
        if(grantResults.length>0){
            for (int state:grantResults){
                if(state!=PackageManager.PERMISSION_GRANTED){
                    isPermission=false;
                    break;
                }
            }
        }
        if(isPermission){
            onPermission(requestCode);
        }else{
            Toast.makeText(this,getString(R.string.permission_title),Toast.LENGTH_LONG).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void finish() {
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
        }
        try {
            unregisterReceiver(mReceiver);
        }catch (Exception e){
        }
        super.onDestroy();
    }

    static class IHandler extends Handler{
        private WeakReference<UIBase> ui;

        IHandler(UIBase ui) {
            this.ui = new WeakReference<UIBase>(ui);
        }

        @Override
        public void handleMessage(Message msg) {
            if(ui!=null&&ui.get()!=null){
                ui.get().handleMsg(msg);
            }
        }
    }

    class UIBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {//收到网络变化广播
                int realNet = Net.getNetWorkType(UIBase.this);//获取实时新的网络类型
                if (net != realNet) {
                    switch (realNet) {
                        case Net.NONE://无网状态
                            onChangeToNone();
                            break;
                        case Net.WIFI://wifi无线网络状态
                            onChangeToWifi();
                            break;
                        default://其它暂时默认为移动网络状态
                            onChangeToMobile();
                            break;
                    }
                    net = realNet;
                }
            }
            if (action.equals(Constants.BD_EXIT_APP)){
                onExitApp();
            }
            if (action.equals(Constants.BD_LOG_OUT)){
                onLogOut();
            }
            if (action.equals(Constants.BD_FORCE_LOG_OUT)){
                onForceLogOut();
            }
        }
    }

}
